package com.yang.news.exception;

import com.yang.news.model.result.CommonErrorCode;
import com.yang.news.model.result.ResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Billyang
 * @date: 2024/12/15 16:48
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 拦截异常
     */
    @ExceptionHandler(Exception.class)
    public ResultModel<?> error(Exception e, HttpServletRequest request, HttpServletResponse response,
                                HandlerMethod handler) {
        log.error("未知异常:", e);
        return ResultModel.unSuccess(CommonErrorCode.UNKNOWN_EXCEPTION);
    }

    /**
     * 拦截未处理的运行时异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResultModel<?> runtime(BusinessException e, HttpServletRequest request, HttpServletResponse response,
                             HandlerMethod handler) {
        log.error("业务异常", e);
        return ResultModel.unSuccess(e.getCode());
    }

}
